<template>
  <div class="list-root">
    <!-- 0.导航 -->
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片视图 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="pageInfo.query" clearable @clear="getGoodsList()">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2.5">
          <el-button type="primary">添加商品</el-button>
        </el-col>
        <el-col :span="6">
          <el-dropdown split-button type="primary" @command="handleCommand">
            点击下载
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="pdf">导出PDF</el-dropdown-item>
              <el-dropdown-item command="excel">导出Execl</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <!-- 2、角色列表 :data绑定数据 -->
      <el-table :data="goodsList" border style="width: 100%" :header-cell-style="headerCellStyle">
        <el-table-column type="index" label="序号" width="100" align="center"> </el-table-column>
        <el-table-column show-overflow-tooltip prop="goods_name" label="商品名称" width="300" align="center">
        </el-table-column>
        <el-table-column prop="goods_price" label="价格" width="120" align="center"> </el-table-column>
        <el-table-column prop="goods_number" label="数量" width="120" align="center"> </el-table-column>
        <el-table-column prop="add_time" label="创建日期" width="200" align="center">
          <template v-slot="scope">
            {{ scope.row.add_time | formateDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="编辑商品" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini">修改</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除商品" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="delGoods(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 4、分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="pageInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
import request from '@/utils/request.js'
export default {
  name: '',
  data() {
    return {
      //1、商品的分页列表
      goodsList: [],
      //2、分页信息
      pageInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
        total: 0
      },
      headerCellStyle: {
        backgroundColor: '#409EFF',
        color: '#ffffff',
        textAlign: 'center'
      }
    }
  },
  methods: {
    //删除商品
    async delGoods(goods) {
      //确认框 confirmRes=cancel/confirm
      let confirmRes = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        //点击取消会抛出异常
        cancelButtonText: '取消删除',
        type: 'warning'
      }).catch(e => e)
      console.log(confirmRes)
      //如果点击的是取消，提示你取消了删除 this.$message.info("")
      if (confirmRes === 'cancel') {
        return this.$message.info('你取消了删除操作')
      }
      let option = {
        url: 'goods/' + goods.goods_id,
        type: 'delete'
      }
      let { data: res } = await request(option)
      console.log(res)
      this.$message.success('删除成功')
      //重新加载页面的数据
      this.getGoodsList()
    },
    //1、获得商品列表信息
    async getGoodsList() {
      let options = {
        url: 'goods',
        type: 'get',
        data: this.pageInfo
      }
      let { data: res } = await request(options)
      //请求失败执行的操作
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.goodsList = res.data.goods
      this.pageInfo.total = res.data.total
      console.log(res.data)
    },

    //6、点击下拉列表时触发的函数
    handleCommand(command) {
      if (command === 'excel') {
        this.exportExcel()
      } else if (command === 'pdf') {
        this.exprotPDF()
      }
    },
    //5、导出excel
    exportExcel() {
      console.log('excel')
      let arr = JSON.parse(JSON.stringify(this.goodsList))
      //如果goodsList是空的
      if (!arr.length) {
        return this.$message.error('导出的数据为空')
      }
      //1、设置表头标题，以逗号隔开，每个逗号就是一个单元格，以对象的属性为表头
      let object = arr[0]
      //获得元素对象的属性名称数组String[]
      let attrs = Object.keys(object)
      //对象没有属性
      if (!attrs.length) {
        return this.$message.error('对象是空对象')
      }
      let str = attrs.join(',')
      str += '\n'
      //2、拼接对象的属性名称，增加\t不让表格显示科学计数法或者其他格式
      for (let i = 0; i < arr.length; i++) {
        for (let item in arr[i]) {
          str += `${arr[i][item] + '\t'},`
        }
        str += '\n'
      }
      //3、encodeURIComponent解决中文乱码
      let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str)
      //4、通过创建a标签实现文件下载
      let link = document.createElement('a')
      //5、设置a标签的链接
      link.href = uri
      //6、对下载的文件命名
      link.download = 'json数据表.csv'
      //7、在页面拼接a标签
      document.body.appendChild(link)
      //8、模拟a标签的点击事件
      link.click()
      //9、清除a标签元素
      document.body.removeChild(link)
    },
    //4、导出pdf
    exprotPDF() {
      let ele = document.getElementById('goodsTable')
      console.log(ele)
      ele.style.background = '#ffffff'
      let eleW = ele.offsetWidth // 获得该容器的宽
      let eleH = ele.offsetHeight // 获得该容器的高
      let eleOffsetTop = ele.offsetTop // 获得该容器到文档顶部的距离
      let eleOffsetLeft = ele.offsetLeft // 获得该容器到文档最左的距离
      let canvas = document.createElement('canvas')
      let abs = 0
      let win_in = document.documentElement.clientWidth || document.body.clientWidth // 获得当前可视窗口的宽度（不包含滚动条）
      let win_out = window.innerWidth // 获得当前窗口的宽度（包含滚动条）
      if (win_out > win_in) {
        // abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
        abs = (win_out - win_in) / 2 // 获得滚动条宽度的一半
        // console.log(a, '新abs');
      }
      canvas.width = eleW * 2 // 将画布宽&&高放大两倍
      canvas.height = eleH * 2
      let context = canvas.getContext('2d')
      context.scale(2, 2)
      context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
      // 这里默认横向没有滚动条的情况，因为offset.left(),有无滚动条的时候存在差值，因此
      // translate的时候，要把这个差值去掉
      // html2canvas(element).then( (canvas)=>{ //报错
      // html2canvas(element[0]).then( (canvas)=>{
      html2canvas(ele, {
        dpi: 300,
        // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
        useCORS: true //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
      }).then(canvas => {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        //一页pdf显示html页面生成的canvas高度;
        let pageHeight = (contentWidth / 592.28) * 841.89
        //未生成pdf的html页面高度
        let leftHeight = contentHeight
        //页面偏移
        let position = 0
        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        let imgWidth = 595.28
        let imgHeight = (595.28 / contentWidth) * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let pdf = new JsPDF('', 'pt', 'a4')
        //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          //在pdf.addImage(pageData, 'JPEG', 左，上，宽度，高度)设置在pdf中显示；
          pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          //pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
        } else {
          // 分页
          while (leftHeight > 0) {
            pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            //避免添加空白页
            if (leftHeight > 0) {
              pdf.addPage()
            }
          }
        }
        //可动态生成
        pdf.save('goods.pdf')
      })
      console.log('pdf')
    },
    //3、每页显示条数变化时触发的函数
    handleSizeChange(size) {
      this.pageInfo.pagesize = size
      this.getGoodsList()
    },
    //2、页码变化时触发的函数
    handleCurrentChange(num) {
      this.pageInfo.pagenum = num
      this.getGoodsList()
    }
  },
  created() {
    this.getGoodsList()
  },
  mounted() {}
}
</script>
